<template>
  <div class="add-item-container">
    <el-container>
      <el-header class="form-header">
        <div class="page-title">新增物品</div>
      </el-header>
      
      <el-main class="form-main">
        <el-form 
          :model="formData" 
          :rules="rules" 
          ref="formRef" 
          label-width="80px" 
          class="item-form">
          
          <!-- 基础信息 -->
          <div class="form-section">
            <div class="section-title">基础信息</div>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="物品编号" prop="itemCode">
                  <div style="display: flex; gap: 8px;">
                    <el-input 
                      v-model="formData.itemCode" 
                      :placeholder="formData.isSystem ? '系统自动生成' : '请手动输入物品编号'" 
                      :disabled="formData.isSystem"
                      :readonly="formData.isSystem"
                      style="flex: 1;"
                    />
                    <el-button 
                      v-if="formData.isSystem" 
                      type="primary" 
                      size="small" 
                      @click="generateItemCode"
                      title="重新生成编号"
                    >
                      <el-icon><Refresh /></el-icon>
                    </el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="" prop="isSystem">
                  <el-checkbox v-model="formData.isSystem" @change="handleSystemCodeChange">系统编号</el-checkbox>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物品名称" prop="itemName">
                  <el-input v-model="formData.itemName" placeholder="请输入物品名称" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="规格型号" prop="specification">
                  <el-input v-model="formData.specification" placeholder="请输入规格型号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="单位" prop="unit">
                  <el-input v-model="formData.unit" placeholder="请选择单位" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="条码" prop="barcode">
                  <el-input v-model="formData.barcode" placeholder="请输入条码" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="制造商型号" prop="manufacturerModel">
                  <el-input v-model="formData.manufacturerModel" placeholder="请输入制造商型号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物品类别" prop="itemType">
                  <el-input v-model="formData.itemType" placeholder="请选择物品类别" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="品牌" prop="brand">
                  <el-input v-model="formData.brand" placeholder="请输入品牌" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="物品属性" prop="itemattributes">
                  <el-select v-model="formData.itemattributes" placeholder="请选择物品属性" style="width: 100%">
                    <el-option label="原材料" value="原材料" />
                    <el-option label="半成品" value="半成品" />
                    <el-option label="成品" value="成品" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="物品分类" prop="itemclassificationId">
                  <el-cascader
                    v-model="formData.itemCategory"
                    :options="categoryOptions"
                    :props="cascaderProps"
                    placeholder="请选择物品分类"
                    clearable
                    filterable
                    style="width: 100%"
                    @change="handleCategoryChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="库存上下限" prop="storageLimit">
                  <div class="limit-input-group">
                    <el-input v-model="formData.storageLowerLimit" placeholder="请输入最小库存数" type="number" />
                    <span class="limit-separator">~</span>
                    <el-input v-model="formData.storageUpperLimit" placeholder="请输入最大库存数" type="number" />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="物品有效期" prop="itemexpiration">
                  <el-input v-model="formData.itemexpiration" placeholder="请输入产品有效期" />
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="" prop="expirationUnit">
                  <el-select v-model="formData.expirationUnit" placeholder="天" style="width: 100%">
                    <el-option label="天" value="天" />
                    <el-option label="月" value="月" />
                    <el-option label="年" value="年" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <span class="unit-label">无</span>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="报警天数" prop="alertDays">
                  <div class="alert-input-group">
                    <el-input v-model="formData.alertDays" placeholder="请输入报警天数" type="number" />
                    <span class="unit-text">天</span>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="状态" prop="state">
                  <el-checkbox v-model="formData.state" :true-label="1" :false-label="0">启用</el-checkbox>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="采购单价" prop="purchaseprice">
                  <el-input v-model="formData.purchaseprice" placeholder="请输入采购单价（含税）" type="number" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="销售单价" prop="salePrice">
                  <el-input v-model="formData.salePrice" placeholder="请输入销售单价（含税）" type="number" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备注" prop="itemsremark">
                  <el-input 
                    v-model="formData.itemsremark" 
                    type="textarea" 
                    :rows="3" 
                    placeholder="请输入备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          
          <!-- 多级售价 -->
          <div class="form-section">
            <div class="section-title">多级售价</div>
            
            <el-table :data="priceData" border class="price-table">
              <el-table-column prop="level" label="客户等级" width="200">
                <template #default="scope">
                  <div class="level-label">{{ scope.row.level }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="discount" label="折扣%" width="200">
                <template #default="scope">
                  <el-input v-model="scope.row.discount" placeholder="请输入" />
                </template>
              </el-table-column>
              <el-table-column prop="price" label="对应售价">
                <template #default="scope">
                  <el-input v-model="scope.row.price" placeholder="请输入" />
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 包装信息 -->
          <div class="form-section">
            <div class="section-title">包装信息</div>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="包装要求" prop="packagingRequirement">
                  <el-select v-model="formData.packagingRequirement" placeholder="请选择包装要求" style="width: 100%">
                    <el-option label="普通包装" value="normal" />
                    <el-option label="特殊包装" value="special" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="包装尺寸" prop="packagingSize">
                  <el-input v-model="formData.packagingSize" placeholder="请输入包装尺寸" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="包装方式" prop="packagingMethod">
                  <el-select v-model="formData.packagingMethod" placeholder="请选择包装方式" style="width: 100%">
                    <el-option label="盒装" value="box" />
                    <el-option label="袋装" value="bag" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          
          <!-- 辅助单位 -->
          <div class="form-section">
            <div class="section-title">辅助单位</div>
            
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="是否开启" prop="enableAuxiliaryUnit">
                  <el-checkbox v-model="formData.enableAuxiliaryUnit">开启</el-checkbox>
                </el-form-item>
              </el-col>
            </el-row>
            
            <div class="auxiliary-unit-fields" style="margin-bottom: 20px;">
              <el-row :gutter="20">
                <el-col :span="6">
                  <div class="field-header">单位名称</div>
                  <el-input v-model="currentAuxiliaryUnit.unitName" placeholder="请选择单位" />
                </el-col>
                <el-col :span="6">
                  <div class="field-header">换算关系</div>
                  <div class="conversion-group">
                    <el-input v-model="currentAuxiliaryUnit.conversionValue" placeholder="请输入" />
                    <span class="conversion-unit">台</span>
                    <span class="conversion-text">主单位</span>
                    <el-input v-model="currentAuxiliaryUnit.mainUnitValue" placeholder="请输入" />
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="field-header">单位类型</div>
                  <el-input v-model="currentAuxiliaryUnit.unitType" placeholder="单位类型" />
                </el-col>
                <el-col :span="6">
                  <div class="field-header">操作</div>
                  <div class="action-buttons">
                    <el-button type="primary" size="small" @click="addAuxiliaryUnit">添加</el-button>
                    <el-button type="danger" size="small" @click="clearCurrentAuxiliaryUnit">移除</el-button>
                  </div>
                </el-col>
              </el-row>
            </div>
            
            <el-table :data="auxiliaryUnitData" border class="auxiliary-table" v-if="auxiliaryUnitData.length > 0">
              <el-table-column prop="unitName" label="单位名称" width="150">
                <template #default="scope">
                  <span>{{ scope.row.unitName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="conversionRate" label="换算关系" width="300">
                <template #default="scope">
                  <span>{{ scope.row.conversionRate }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="unitType" label="单位类型" width="150">
                <template #default="scope">
                  <span>{{ scope.row.unitType }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeAuxiliaryUnit(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 产品图片 -->
          <div class="form-section">
            <div class="section-title">产品图片</div>
            
            <el-form-item label="产品图片" prop="productImage" class="upload-item">
              <el-upload
                class="avatar-uploader"
                :action="uploadImageUrl"
                :show-file-list="false"
                :on-success="handleImageUploadSuccess"
                :before-upload="beforeImageUpload"
              >
                <img v-if="formData.itemsimg" :src="formData.itemsimg" class="avatar" />
                <div v-else class="upload-box">
                  <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                  <div class="upload-text">点击上传图片</div>
                </div>
              </el-upload>
              
              <!-- 显示删除按钮 -->
              <div v-if="formData.itemsimg" class="image-actions">
                <el-button type="danger" size="small" @click="removeCurrentImage">删除图片</el-button>
              </div>
              <div class="upload-tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-form-item>
          </div>
          
          <!-- 附件 -->
          <div class="form-section">
            <div class="section-title">附件</div>
            <div class="attachment-section">
              <div class="attachment-left">
                <div v-if="uploadedFiles.length === 0" class="no-files">
                  暂无附件
                </div>
                <div v-else>
                  <div v-for="(attachment, index) in uploadedFiles" :key="index" class="file-item">
                    <div class="file-info">
                      <div class="file-name" @click="previewFile(attachment)" :title="attachment.fileName">
                        {{ attachment.fileName }}
                      </div>
                      <div class="file-details">
                        <div>文件大小：{{ formatFileSize(attachment.fileSize) }}</div>
                        <div>上传时间：{{ attachment.uploadTime }}</div>
                      </div>
                    </div>
                    <div class="file-actions">
                      <el-button link type="primary" @click="updateFile(index)">更新上传</el-button>
                      <el-button link type="danger" @click="deleteFile(index)">删除</el-button>
                    </div>
                  </div>
                </div>
              </div>
              <div class="attachment-right">
                <el-upload
                  class="upload-area"
                  drag
                  :action="''"
                  multiple
                  :auto-upload="false"
                  :on-change="handleFileChange"
                  :show-file-list="false"
                  :accept="'.pdf,.doc,.docx,.xls,.xlsx,.png,.jpg,.jpeg,.txt'">
                  <div class="upload-content">
                    <el-icon class="upload-icon"><UploadFilled /></el-icon>
                    <div>点击上传 / 拖拽到此区域</div>
                    <div class="upload-hint">支持 PDF、Word、Excel、图片等格式</div>
                    <div class="upload-buttons">
                      <el-button type="primary" size="small" @click="handleBatchUpload">批量上传</el-button>
                    </div>
                  </div>
                </el-upload>
              </div>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="form-actions">
            <el-button @click="handleCancel">关闭</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </div>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { UploadFile } from 'element-plus'
import { Plus, Upload, UploadFilled, Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { uploadFile as apiUploadFile, getItemCategoryTree, addItem } from '@/Https/server'

const router = useRouter()

// 图片上传URL
const uploadImageUrl = ref('http://8.141.112.218:5080/api/FileUpload/UploadFile')

// 定义附件接口
interface AttachmentItem {
  id?: number;
  fileName: string;
  fileSize: number;
  uploadTime: string;
  fileUrl?: string;
}



// 定义分类选项接口
interface CategoryOption {
  values: any;
  label: string;
  children?: CategoryOption[];
}

// 表单数据
const formData = reactive({
  itemCode: '',
  isSystem: true,
  itemName: '',
  itemType: '',
  specification: '',
  unit: '',
  brand: '',
  itemclassificationId: 0,
  itemexpiration: '',
  state: 0,
  purchaseprice: '',
  salePrice: '',
  barcode: '',
  manufacturerModel: '',
  itemattributes: '',
  upper: '',
  number: '',
  totalinventory: '',
  itemsimg: '',
  isAuxiliaryUnits: false,
  auxiliaryUnits: [],
  itemsremark: '',
  tieredPricings: [],
  packagingInformation: {
    cartonSize: '',
    packagingRequirements: '',
    packingMethod: ''
  },
  attachments: [],
  operatorId: 1, // 设置默认操作人ID
  createName: '系统用户', // 设置默认创建人名称
  ipAddress: '',
  // 前端辅助字段
  itemCategory: [] as any[],
  itemSubCategory: '',
  storageLowerLimit: '',
  storageUpperLimit: '',
  regularPrice: '',
  packagingRequirement: '',
  packagingSize: '',
  packagingMethod: '',
  enableAuxiliaryUnit: false,
  expirationUnit: '天',
  alertDays: ''
})

// 分类选项数据
const categoryOptions = ref<CategoryOption[]>([])

// 级联选择器配置
const cascaderProps = {
  value: 'values',
  label: 'label',
  children: 'children',
  checkStrictly: true, // 允许选择任意级别
  emitPath: false // 只返回最后选中的值(ID)
}

// 加载物品分类数据
const loadCategoryData = async () => {
  try {
    console.log('开始加载物品分类数据...')
    const response: any = await getItemCategoryTree()
    console.log('物品分类API响应:', response)
    
    if (response && response.code === 200) {
      console.log('物品分类数据:', response.data)
      categoryOptions.value = response.data || []
      console.log('设置后的categoryOptions:', categoryOptions.value)
    } else {
      console.error('API返回错误:', response)
      ElMessage.error(`加载物品分类失败: ${response?.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('加载物品分类错误:', error)
    ElMessage.error('加载物品分类失败，请重试')
  }
}

// 处理分类选择变化
const handleCategoryChange = (value: any) => {
  console.log('选择的物品分类:', value)
  if (value) {
    // 找到选中的分类节点
    const findCategoryName = (list: CategoryOption[], targetValue: any): string => {
      for (const item of list) {
        if (item.values === targetValue) {
          return item.label;
        }
        if (item.children && item.children.length > 0) {
          const result = findCategoryName(item.children, targetValue);
          if (result) return result;
        }
      }
      return '';
    };
    
    // 直接使用选中的值作为ID（因为emitPath: false只返回最后选中的值）
    formData.itemclassificationId = value;
    formData.itemSubCategory = findCategoryName(categoryOptions.value, value);
    console.log('设置的分类ID:', formData.itemclassificationId)
    console.log('设置的分类名称:', formData.itemSubCategory)
    
    // 手动触发表单验证
    formRef.value?.validateField('itemclassificationId')
  } else {
    formData.itemclassificationId = 0;
    formData.itemSubCategory = '';
  }
}

// 组件挂载时加载分类数据
onMounted(() => {
  loadCategoryData()
  // 如果默认启用系统编号，则初始化生成编号
  if (formData.isSystem) {
    handleSystemCodeChange()
  }
})

// 表单验证规则
const rules = {
  itemCode: [
    { required: true, message: '请输入物品编码', trigger: 'blur' }
  ],
  itemName: [
    { required: true, message: '请输入物品名称', trigger: 'blur' }
  ],
  itemclassificationId: [
    { required: true, message: '请选择物品分类', trigger: 'change' }
  ],
  specification: [
    { required: true, message: '请输入物品规格', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  itemattributes: [
    { required: true, message: '请选择物品属性', trigger: 'change' }
  ]
}

// 多级售价数据
const priceData = ref([
  { level: '等级一', discount: '', price: '' },
  { level: '等级二', discount: '', price: '' },
  { level: '等级三', discount: '', price: '' },
  { level: '等级四', discount: '', price: '' },
  { level: '等级五', discount: '', price: '' },
  { level: '等级六', discount: '', price: '' }
])

// 辅助单位数据
const auxiliaryUnitData = ref<{unitName: string; conversionRate: string; unitType: string}[]>([])

// 当前编辑的辅助单位
const currentAuxiliaryUnit = reactive({
  unitName: '',
  conversionValue: '',
  mainUnitValue: '',
  unitType: ''
})

// 上传相关
const uploadedFiles = ref<AttachmentItem[]>([])

const formRef = ref()

// 添加辅助单位
const addAuxiliaryUnit = () => {
  if (!currentAuxiliaryUnit.unitName || !currentAuxiliaryUnit.conversionValue || !currentAuxiliaryUnit.mainUnitValue) {
    ElMessage.warning('请填写完整的辅助单位信息')
    return
  }
  
  const conversionRate = `${currentAuxiliaryUnit.conversionValue}台主单位${currentAuxiliaryUnit.mainUnitValue}`
  
  auxiliaryUnitData.value.push({
    unitName: currentAuxiliaryUnit.unitName,
    conversionRate: conversionRate,
    unitType: currentAuxiliaryUnit.unitType
  })
  
  // 清空当前输入
  clearCurrentAuxiliaryUnit()
  ElMessage.success('辅助单位添加成功')
}

// 清除当前辅助单位输入
const clearCurrentAuxiliaryUnit = () => {
  currentAuxiliaryUnit.unitName = ''
  currentAuxiliaryUnit.conversionValue = ''
  currentAuxiliaryUnit.mainUnitValue = ''
  currentAuxiliaryUnit.unitType = ''
}

// 删除辅助单位
const removeAuxiliaryUnit = (index: number) => {
  auxiliaryUnitData.value.splice(index, 1)
}

// 图片上传成功回调
const handleImageUploadSuccess = (response: any) => {
  console.log('图片上传成功:', response);
  // 根据后端API，直接返回图片URL字符串
  formData.itemsimg = response;
  ElMessage.success('图片上传成功');
};

// 图片上传前验证
const beforeImageUpload = (file: any) => {
  const isImage = file.type.startsWith('image/');
  const isLt500K = file.size / 1024 < 500;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt500K) {
    ElMessage.error('图片大小不能超过 500KB!');
    return false;
  }
  return true;
};

// 删除当前图片
const removeCurrentImage = () => {
  formData.itemsimg = '';
  ElMessage.success('图片已删除');
};

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 格式化时间
const formatTime = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 处理文件选择变化
const handleFileChange = async (uploadFile: UploadFile) => {
  if (!uploadFile.raw) return;
  
  try {
    // 显示上传中消息
    ElMessage.info('正在上传文件...');
    
    // 调用单文件上传API
    const response: any = await apiUploadFile(uploadFile.raw);
    
    if (response) {
      // 添加到附件列表
      const newAttachment: AttachmentItem = {
        fileName: uploadFile.name,
        fileSize: uploadFile.size || 0,
        uploadTime: formatTime(new Date()),
        fileUrl: response // 后端返回的文件URL
      };
      
      uploadedFiles.value.push(newAttachment);
      ElMessage.success(`文件 "${uploadFile.name}" 上传成功`);
    } else {
      ElMessage.error('文件上传失败');
    }
  } catch (error) {
    console.error('文件上传错误:', error);
    ElMessage.error('文件上传失败，请重试');
  }
};

// 批量上传文件
const handleBatchUpload = () => {
  // 创建隐藏的文件输入元素
  const input = document.createElement('input');
  input.type = 'file';
  input.multiple = true;
  input.accept = '.pdf,.doc,.docx,.xls,.xlsx,.png,.jpg,.jpeg,.txt';
  
  input.onchange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    const files = Array.from(target.files || []);
    
    if (files.length === 0) return;
    
    // 显示上传中消息
    ElMessage.info(`正在上传 ${files.length} 个文件...`);
    
    let successCount = 0;
    let failedCount = 0;
    
    // 逐个调用单文件上传API
    for (const file of files) {
      try {
        const response: any = await apiUploadFile(file);
        
        if (response) {
          // 添加到附件列表
          const newAttachment: AttachmentItem = {
            fileName: file.name,
            fileSize: file.size,
            uploadTime: formatTime(new Date()),
            fileUrl: response // 后端返回的文件URL
          };
          
          uploadedFiles.value.push(newAttachment);
          successCount++;
        } else {
          failedCount++;
          console.error(`文件 "${file.name}" 上传失败`);
        }
      } catch (error) {
        failedCount++;
        console.error(`文件 "${file.name}" 上传错误:`, error);
      }
    }
    
    // 显示上传结果
    if (successCount > 0 && failedCount === 0) {
      ElMessage.success(`成功上传 ${successCount} 个文件`);
    } else if (successCount > 0 && failedCount > 0) {
      ElMessage.warning(`上传完成：${successCount} 个成功，${failedCount} 个失败`);
    } else {
      ElMessage.error('所有文件上传失败，请重试');
    }
  };
  
  input.click();
};

// 更新文件
const updateFile = (index: number) => {
  // 创建隐藏的文件输入元素
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.pdf,.doc,.docx,.xls,.xlsx,.png,.jpg,.jpeg,.txt';
  
  input.onchange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    
    if (!file) return;
    
    try {
      // 显示上传中消息
      ElMessage.info('正在更新文件...');
      
      // 调用单文件上传API
      const response: any = await apiUploadFile(file);
      
      if (response) {
        // 更新附件信息
        uploadedFiles.value[index] = {
          fileName: file.name,
          fileSize: file.size,
          uploadTime: formatTime(new Date()),
          fileUrl: response
        };
        
        ElMessage.success(`文件更新成功`);
      } else {
        ElMessage.error('文件更新失败');
      }
    } catch (error) {
      console.error('文件更新错误:', error);
      ElMessage.error('文件更新失败，请重试');
    }
  };
  
  input.click();
};

// 删除文件
const deleteFile = (index: number) => {
  const fileName = uploadedFiles.value[index].fileName;
  uploadedFiles.value.splice(index, 1);
  ElMessage.success(`文件 "${fileName}" 已删除`);
};

// 预览文件
const previewFile = (attachment: AttachmentItem) => {
  if (attachment.fileUrl) {
    // 在新窗口中打开文件
    window.open(attachment.fileUrl, '_blank');
  } else {
    ElMessage.warning('文件URL不存在，无法预览');
  }
};

// 文件上传成功（保留旧方法名以防模板使用）
const handleFileUploadSuccess = handleFileChange;



// 文件上传前检查
const beforeFileUpload = (file: any) => {
  const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
  const isAllowed = allowedTypes.includes(file.type)
  
  if (!isAllowed) {
    ElMessage.error('只能上传PDF、DOC、DOCX格式文件!')
    return false
  }
  return true
}

// 处理系统编号勾选变化
const handleSystemCodeChange = () => {
  if (formData.isSystem) {
    // 如果勾选了系统编号，则自动生成编号
    generateItemCode()
    ElMessage.success('物品编号已自动生成')
  } else {
    // 如果取消勾选，则清空编号
    formData.itemCode = ''
    ElMessage.info('请手动输入物品编号')
  }
}

// 生成物品编号
const generateItemCode = () => {
  const currentDate = new Date()
  const year = currentDate.getFullYear()
  const month = String(currentDate.getMonth() + 1).padStart(2, '0')
  const day = String(currentDate.getDate()).padStart(2, '0')
  const hour = String(currentDate.getHours()).padStart(2, '0')
  const minute = String(currentDate.getMinutes()).padStart(2, '0')
  const second = String(currentDate.getSeconds()).padStart(2, '0')
  
  // 添加3位随机数确保唯一性
  const randomNum = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
  
  // 格式：WPH + 年月日时分秒 + 3位随机数
  formData.itemCode = `WPH${year}${month}${day}${hour}${minute}${second}${randomNum}`
  
  console.log('生成的物品编号:', formData.itemCode)
}


// 提交表单
const handleSubmit = async () => {
  try {
    // 首先进行表单验证
    await formRef.value.validate()
    
    // 验证必填字段
    if (!formData.itemCode?.trim()) {
      ElMessage.error('请输入物品编码')
      return
    }
    if (!formData.itemName?.trim()) {
      ElMessage.error('请输入物品名称')
      return
    }
    if (!formData.itemclassificationId || formData.itemclassificationId <= 0) {
      ElMessage.error('请选择物品分类')
      return
    }
    if (!formData.specification?.trim()) {
      ElMessage.error('请输入物品规格')
      return
    }
    if (!formData.unit?.trim()) {
      ElMessage.error('请输入单位')
      return
    }
    if (!formData.itemattributes?.trim()) {
      ElMessage.error('请选择物品属性')
      return
    }
    
    // 构造库存上下限字符串
    const upperLimit = formData.storageLowerLimit && formData.storageUpperLimit 
      ? `${formData.storageLowerLimit}~${formData.storageUpperLimit}` 
      : ''
    
    // 构造物品有效期（如果有数值，转为日期）
    let itemExpiration = null;
    if (formData.itemexpiration) {
      const days = Number(formData.itemexpiration);
      if (!isNaN(days) && days > 0) {
        const currentDate = new Date();
        const expirationDate = new Date(currentDate);
        
        if (formData.expirationUnit === '天') {
          expirationDate.setDate(currentDate.getDate() + days);
        } else if (formData.expirationUnit === '月') {
          expirationDate.setMonth(currentDate.getMonth() + days);
        } else if (formData.expirationUnit === '年') {
          expirationDate.setFullYear(currentDate.getFullYear() + days);
        }
        
        itemExpiration = expirationDate.toISOString();
      }
    }
    
    // 构造提交数据，严格匹配后端API参数结构
    const submitData = {
      // 必填字段
      itemCode: formData.itemCode.trim(),
      itemName: formData.itemName.trim(),
      specification: formData.specification.trim(),
      unit: formData.unit.trim(),
      itemattributes: formData.itemattributes.trim(),
      itemclassificationId: formData.itemclassificationId,
      operatorId: 1, // 必填：设置默认操作人ID
      createName: '系统用户', // 必填：设置默认创建人名称
      
      // 可选字段，确保数据类型正确
      itemType: formData.itemType?.trim() || null,
      brand: formData.brand?.trim() || null,
      itemexpiration: itemExpiration,
      state: formData.state ? 1 : 0,
      purchaseprice: formData.purchaseprice && !isNaN(Number(formData.purchaseprice)) ? Number(formData.purchaseprice) : null,
      salePrice: formData.salePrice && !isNaN(Number(formData.salePrice)) ? Number(formData.salePrice) : null,
      barcode: formData.barcode?.trim() || null,
      manufacturerModel: formData.manufacturerModel?.trim() || null,
      upper: upperLimit || null,
      number: formData.alertDays && !isNaN(Number(formData.alertDays)) ? Number(formData.alertDays) : null,
      totalinventory: formData.totalinventory && !isNaN(Number(formData.totalinventory)) ? Number(formData.totalinventory) : null,
      itemsimg: formData.itemsimg?.trim() || null,
      isAuxiliaryUnits: Boolean(formData.enableAuxiliaryUnit),
      auxiliaryUnits: auxiliaryUnitData.value.length > 0 ? auxiliaryUnitData.value.map(unit => {
        // 解析换算关系，提取数值部分
        const conversionMatch = unit.conversionRate.match(/(\d+(?:\.\d+)?)台主单位(\d+(?:\.\d+)?)/);
        let conversionValue = 1;
        
        if (conversionMatch) {
          const auxValue = Number(conversionMatch[1]);
          const mainValue = Number(conversionMatch[2]);
          // 换算关系 = 辅助单位值 / 主单位值，表示1个主单位等于多少个辅助单位
          conversionValue = mainValue / auxValue;
        }
        
        return {
          unitname: unit.unitName?.trim() || '',
          unitrelationship: !isNaN(conversionValue) ? conversionValue : 1,
          unitbarcode: unit.unitType?.trim() || null
        }
      }) : [],
      itemsremark: formData.itemsremark?.trim() || null,
      tieredPricings: priceData.value
        .filter(price => price.level && (price.discount || price.price))
        .map(price => ({
          customerlevel: price.level?.trim() || '',
          discount: price.discount && price.discount.toString().trim() && !isNaN(Number(price.discount)) ? Number(price.discount) : null,
          correspondingPrice: price.price && price.price.toString().trim() && !isNaN(Number(price.price)) ? Number(price.price) : null
        })) || [],
      packagingInformation: (formData.packagingSize || formData.packagingRequirement || formData.packagingMethod) ? {
        cartonSize: formData.packagingSize?.trim() || null,
        packagingRequirements: formData.packagingRequirement?.trim() || null,
        packingMethod: formData.packagingMethod?.trim() || null
      } : null,
      attachments: uploadedFiles.value.length > 0 ? uploadedFiles.value.map(file => ({
        id: 0,
        filename: file.fileName?.trim() || '',
        filepath: file.fileUrl?.trim() || '',
        filesize: file.fileSize || 0
      })) : [],
      ipAddress: null // 后端会自动获取IP地址
    }
    
    console.log('提交表单数据:', submitData)
    console.log('表单数据JSON:', JSON.stringify(submitData, null, 2))
    
    // 调用API
    try {
      const response: any = await addItem(submitData)
      console.log('API完整响应:', response)
      
      if (response && response.code === 200) {
        ElMessage.success('物品添加成功')
        // 成功后跳转到物品显示界面
        setTimeout(() => {
          router.push('/ShowItems')
        }, 1500)
      } else {
        // 处理业务逻辑错误
        const errorMessage = response?.message || response?.data?.message || '物品添加失败'
        console.error('API业务错误详情:', response)
        ElMessage.error(`添加失败: ${errorMessage}`)
      }
    } catch (apiError: any) {
      console.error('API调用错误:', apiError)
      
      // 处理网络错误和服务器错误
      if (apiError.response) {
        // 服务器返回了错误状态码
        const status = apiError.response.status
        const data = apiError.response.data
        
        console.error(`HTTP ${status} 错误详情:`, data)
        
        if (status === 500) {
          const serverError = data?.message || data?.Message || data?.error || '服务器内部错误'
          ElMessage.error(`服务器错误: ${serverError}`)
        } else if (status === 400) {
          const validationError = data?.message || data?.Message || data?.error || '请求参数错误'
          ElMessage.error(`参数错误: ${validationError}`)
        } else if (status === 401) {
          ElMessage.error('请先登录')
        } else if (status === 403) {
          ElMessage.error('权限不足')
        } else if (status === 404) {
          ElMessage.error('API接口不存在')
        } else {
          ElMessage.error(`请求失败 (${status}): ${data?.message || data?.Message || data?.error || '未知错误'}`)
        }
      } else if (apiError.request) {
        // 网络错误
        ElMessage.error('网络连接失败，请检查网络连接后重试')
        console.error('网络错误:', apiError.request)
      } else {
        // 其他错误
        ElMessage.error(`请求配置错误: ${apiError.message}`)
        console.error('配置错误:', apiError.message)
      }
    }
  } catch (error: any) {
    console.error('表单验证或其他错误:', error)
    if (error.message === 'Validation failed') {
      ElMessage.error('请检查表单填写是否完整')
    } else {
      ElMessage.error('操作失败，请重试')
    }
  }
}

// 返回/取消
const handleCancel = () => {
  router.push('/ShowItems')
}
</script>

<style scoped>
.add-item-container {
  background: #f5f5f5;
  min-height: 100vh;
}

.form-header {
  background: white;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  padding: 0 20px;
  height: 60px !important;
  flex-shrink: 0;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.form-main {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
  position: relative;
  min-height: 0;
}

.item-form {
  background: white;
  padding: 30px 30px 100px 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative;
  margin-bottom: 20px;
}

.form-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
}



.price-table,
.auxiliary-table {
  width: 100%;
  margin-bottom: 20px;
}

.upload-demo {
  margin-bottom: 20px;
}

.uploaded-images {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
}

.image-item {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 10px;
  width: 200px;
}

.image-item img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.image-actions,
.file-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.uploaded-files {
  margin-top: 20px;
}

.file-item {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.file-info {
  display: flex;
  gap: 20px;
  align-items: center;
}

.file-name {
  font-weight: 600;
  color: #303133;
}

.file-size,
.file-time {
  color: #909399;
  font-size: 12px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
  padding: 20px 0;
  border-top: 1px solid #e6e6e6;
  background: white;
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  min-width: 200px;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  color: #606266;
  font-weight: 500;
  line-height: 32px;
  padding: 0 8px 0 0;
  font-size: 14px;
}

:deep(.el-row) {
  margin-bottom: 0;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  width: 100%;
  height: 180px;
  text-align: center;
  background: #fafafa;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409eff;
}

:deep(.el-icon--upload) {
  font-size: 67px;
  color: #c0c4cc;
  margin: 40px 0 16px;
}

:deep(.el-upload__text) {
  color: #606266;
  font-size: 14px;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
}

/* 附件部分样式 */
.attachment-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.attachment-left {
  flex: 1;
}

.attachment-right {
  flex: 1;
}

.file-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
  margin-bottom: 10px;
}

.file-info {
  margin-bottom: 10px;
}

.file-name {
  font-weight: bold;
  margin-bottom: 5px;
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.file-name:hover {
  color: #66b1ff;
}

.file-details {
  font-size: 12px;
  color: #909399;
}

.file-details div {
  margin-bottom: 2px;
}

.file-actions {
  display: flex;
  gap: 10px;
}

.upload-area {
  width: 100%;
  height: 120px;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

.upload-icon {
  font-size: 32px;
  margin-bottom: 10px;
  color: #c0c4cc;
}

.upload-hint {
  font-size: 12px;
  color: #c0c4cc;
  margin-top: 5px;
}

.no-files {
  text-align: center;
  color: #909399;
  padding: 40px 20px;
  border: 1px dashed #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.upload-buttons {
  margin-top: 15px;
}

.upload-buttons .el-button {
  margin: 0 5px;
}

/* 多级售价等级标签样式 */
.level-label {
  padding: 8px 12px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  color: #606266;
  font-weight: 500;
  text-align: center;
}

/* 库存上下限输入组合样式 */
.limit-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.limit-separator {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
  margin: 0 5px;
}

/* 报警天数输入组合样式 */
.alert-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.unit-text {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.unit-label {
  color: #606266;
  font-size: 14px;
  line-height: 32px;
  display: flex;
  align-items: center;
  height: 32px;
}

/* 辅助单位字段样式 */
.field-header {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  margin-bottom: 8px;
  line-height: 1.2;
}

.conversion-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.conversion-unit,
.conversion-text {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.auxiliary-unit-fields {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

/* 确保容器组件正确处理滚动 */
:deep(.el-container) {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

:deep(.el-main) {
  padding: 0;
  overflow-y: auto;
  flex: 1;
}

:deep(.el-upload-dragger) {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  width: 100%;
  height: 120px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409eff;
}

/* 产品图片上传样式 */
.upload-item {
  margin-bottom: 20px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.upload-box {
  width: 178px;
  height: 178px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-text {
  color: #8c939d;
  font-size: 14px;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.image-actions {
  margin-top: 10px;
  text-align: center;
}
</style> 